package com.api.weavernorth.action.job;


import com.weavernorth.util.JdeUtil;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import sun.misc.BASE64Encoder;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;


@Path("/weavernorth/action/job/Job")
public class Job {
    private static Log log = org.apache.commons.logging.LogFactory.getLog(Job.class.getName());
    @GET
    @Path("/getData")
    @Produces(MediaType.TEXT_PLAIN)
    public String getDatas(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException, DocumentException {
        BaseBean bb =new BaseBean();
        //数据库操作
        RecordSet rs=new RecordSet();
        //获取前端js传入的岗位和入职时间
        String  strGw=request.getParameter("gw");
        String strJobWorkcode="";
        //根据岗位id查询岗位编码
        String sql="select jobtitlecode  from hrmjobtitles where id=? ";
        rs.executeQuery(sql,strGw);
        if(rs.next()){
            strJobWorkcode=Util.null2String(rs.getString("jobtitlecode"));
        }


        log.info("岗位："+strGw+",岗位编码:"+strJobWorkcode);
        String  strRzsj=request.getParameter("rzsj");
        log.info("入职时间："+strRzsj);
        //调用方法
        String strResult = toServices(strJobWorkcode, strRzsj);
        log.info("最终返回值："+strResult);

        return  strResult;
    }
    /**调用接口的方法
     *
     * @return
     */

    public String  toServices(String strGw,String strRzsj){

        String requestXml="<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>"+
                "<soapenv:Header/>"+
                "<soapenv:Body>"+
                "<urn:ZRFC_HR_KB_N>"+
               "<I_DATE>"+strRzsj+"</I_DATE>"+
                "<I_MASSN>Z1</I_MASSN>"+
                "<!--Optional:-->"+
               "<I_PERNR></I_PERNR>"+
                "<I_PLANS>"+strGw+"</I_PLANS>"+
                "</urn:ZRFC_HR_KB_N>"+
                "</soapenv:Body>"+
                "</soapenv:Envelope>";

        BaseBean aa  = new BaseBean();
        aa.writeLog("requestXml："+requestXml);
        //获取properties中接口地址值
        String strRealUrl = Util.null2String(aa.getPropValue("joburl","gwUrl"));
        aa.writeLog("接口地址值："+strRealUrl);
        //调用方法传入的参数
        String strEncoding="UTF-8";
        String result = null;
        try {
            result =sendPost(strRealUrl,requestXml,strEncoding);

            //解析result
            //返回的xml
            log.info("返回的请求体："+result);
            //获取返回结果
            JdeUtil jdeUtil = new JdeUtil();
            String  strKb = jdeUtil.XMLReader(result, "E_KB");
            if(strKb!=null&&strKb.equals("E")){
                String  strMessage = jdeUtil.XMLReader(result, "E_MESSAGE");
                log.info("错误信息："+strMessage);
                return strMessage;
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        log.info("请求地址=" + strUrl);
        log.info("请求xml=" + strRequestXml);

        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);

            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);

            //获取用户名
            String strUsername = Util.null2String(bb.getPropValue("personnel-erdos", "username"));
            //获取密码
            String strPassword = Util.null2String(bb.getPropValue("personnel-erdos", "password"));
            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                // log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }

        return strBody;
    }
}
